import { fetchEventSource } from '@microsoft/fetch-event-source';

interface EventSourceOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  headers?: Record<string, string>;
  body?: any;
  openWhenHidden?: boolean;
  onopen?: (response: Response) => Promise<void> | void;
  onmessage: (event: MessageEvent) => void;
  onclose?: () => void;
  onerror?: (err: any) => void;
}

// 后端服务器基础URL
const BASE_URL = 'http://115.190.159.128:8082';

/**
 * 封装fetchEventSource，用于处理服务器发送事件(SSE)
 * @param url 请求URL
 * @param options 配置选项
 */
export async function fetchEvent<T = any>(
  url: string,
  options: EventSourceOptions
): Promise<void> {
  // 构建完整URL
  const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url.startsWith('/api') ? url : `/api${url}`}`;
  
  // 默认配置
  const defaultOptions: Partial<EventSourceOptions> = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    openWhenHidden: true,
  };

  // 合并配置
  const mergedOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers,
    },
  };

  // 处理请求体
  const config: any = {
    method: mergedOptions.method,
    headers: mergedOptions.headers,
    openWhenHidden: mergedOptions.openWhenHidden,
  };

  // 如果是GET请求，不添加body
  if (mergedOptions.method !== 'GET' && mergedOptions.body) {
    config.body = JSON.stringify(mergedOptions.body);
  }

  try {
    await fetchEventSource(fullUrl, {
      ...config,
      async onopen(response) {
        if (mergedOptions.onopen) {
          await mergedOptions.onopen(response);
        }
      },
      onmessage(event) {
        mergedOptions.onmessage(event);
      },
      onclose() {
        if (mergedOptions.onclose) {
          mergedOptions.onclose();
        }
      },
      onerror(err) {
        if (mergedOptions.onerror) {
          mergedOptions.onerror(err);
        } else {
          // 默认错误处理
          console.error('EventSource error:', err);
          throw err;
        }
      }
    });
  } catch (error) {
    console.error('Failed to connect to EventSource:', error);
    throw error;
  }
}

/**
 * 简化的SSE请求函数，适用于常见的聊天场景
 * @param url 请求URL
 * @param data 请求数据（POST请求时使用）
 * @param onMessage 消息处理回调
 * @param onClose 连接关闭回调
 * @param onError 错误处理回调
 */
export async function chatStream<T = any>(
  url: string,
  data: any,
  onMessage: (event: MessageEvent) => void,
  onClose?: () => void,
  onError?: (err: any) => void
): Promise<void> {
  return fetchEvent<T>(url, {
    method: 'POST',
    body: data,
    onmessage: onMessage,
    onclose: onClose,
    onerror: onError,
  });
}